package com.mycompany.common.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Logger;

import javax.naming.InitialContext;
import javax.sql.DataSource;

/**
 * Created by My Company.
 * User: loitran
 * Date: Feb 29, 2012
 * Time: 1:13:02 PM
 * com.mycompany.common.jdbc.
 */
public class ConnectionDatabase {
	protected transient Logger logger = Logger.getLogger(ConnectionDatabase.class.getName());
	
	public static final String DEFAULT_DATA_SOURCE_NAME ="java:comp/env/jdbc/RestaurantDB";
	public static final String USER ="";
	public static final String PASSWORD="";
	public static Connection connect;
	
	public static Connection getInstance(){
		if(connect == null){
			try{
				//connect = DriverManager.getConnection(DEFAULT_DATA_SOURCE_NAME, USER, PASSWORD);
				DataSource ds = (DataSource)new InitialContext().lookup(DEFAULT_DATA_SOURCE_NAME);
				connect = ds.getConnection();
			}catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
		return connect;
	}
	
	public static final ResultSet executeQuery(PreparedStatement ps) throws SQLException {
		ResultSet rs = ps.executeQuery();
		return rs;
	}
	
	public static final int executeUpdate(PreparedStatement ps) throws SQLException {
		int id = ps.executeUpdate();
		return id;
	}
	
	public static final PreparedStatement preparedStatement(Connection c, String sql) throws SQLException {
		if(c == null) throw new IllegalArgumentException("c can not be null!");
		if((sql == null) || (sql.length() == 0)) throw new IllegalArgumentException("sql can not be null or empty!");
		PreparedStatement ps = c.prepareStatement(sql);
		return ps;
	}
	
	/**
     * Closes the passed statement, resultset and connection if they arent null
     * @param con
     * @param statement
     * @param rs
     */
    protected final void relinquishResources(Connection con, Statement statement, ResultSet rs)
    {
        //Result set first
        try
        {
            if (rs != null)
            {
                rs.close();
            }
        }
        catch (SQLException e)
        {

        }

        //Statement
        try
        {
            if (statement != null)
            {
                statement.close();
            }
        }
        catch (SQLException e)
        {

        }

        //Connection
        try
        {
            if (con != null)
            {
                con.close();
            }
        }
        catch (SQLException e)
        {

        }
    }
}
